package com.gper.edu.vip.struct.proxy.impl;

import java.io.*;

/**
 * @Author: ellis.guan
 * @Description:
 * @Date: 2020/3/2 17:54
 * @Version: 1.0
 */
public class EllisClassLoader extends ClassLoader{
    private File classPathFile;

    public EllisClassLoader() {
        this.classPathFile = new File(EllisClassLoader.class.getResource("").getPath());
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classFullName = EllisClassLoader.class.getPackage().getName()+"."+name;
        if (classPathFile !=null){
            File classFile = new File(classPathFile,name.replaceAll("\\.","/")+".class");
            if (classFile.exists()){
                FileInputStream in = null;
                ByteArrayOutputStream bos = null;
                try{
                    in = new FileInputStream(classFile);
                    bos = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = in.read(bytes)) != -1){
                        bos.write(bytes,0,len);
                    }
                    return defineClass(classFullName,bos.toByteArray(),0,bos.size());
                }catch (Exception e){
                    throw new ClassNotFoundException();
                }finally {
                    closeStream(in, bos);
                    if (classFile != null){
                        classFile.delete();
                    }
                }
            }
        }
        throw new ClassNotFoundException();
    }

    private void closeStream(FileInputStream in, ByteArrayOutputStream bos) {
        if (in != null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bos != null){
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
